package jk.zmn.server.core;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class WebApp {
	
	private static ServletContext context;
	
	static {
		
		//获取解析工厂
		try {
			SAXParserFactory factory =SAXParserFactory.newInstance();
			//获取解析器
			SAXParser sax =factory.newSAXParser();
			//指定xml+处理器
			WebHandler web = new WebHandler();
			sax.parse(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("web.xml")
					,web);
			//得到所有的servlet 和别名
			List<ServletEntity> entityList = web.getEntityList();
			List<MappingEntity> mappingList = web.getMappingList();
			context = new ServletContext();
			//存放servlet 和其对应的别名
			Map<String, String> servletMap = context.getServletMap();
			
			for(ServletEntity servletEntity: entityList) {
				servletMap.put(servletEntity.getName(),servletEntity.getClz());
			}

			//存放urlpatten和servlet别名
			Map<String, String> mappingMap = context.getMappingMap();
			for(MappingEntity mappingEntity:mappingList) {
				List<String> urlPattern = mappingEntity.getUrlPattern();
				for(String url:urlPattern) {
					mappingMap.put(url, mappingEntity.getName());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Servlet getServlet(String url) {
		
		if (url==null || url.trim().equals("")) {
			return null;
		}else {
			String servletname = context.getServletMap().get(context.getMappingMap().get(url));
			
			//要确保该类有空构造函数存在
			try {
				return (Servlet)Class.forName(servletname).newInstance();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				return null;
			}
			
		}
	}

}
